package com.example.demo.security;

import com.example.demo.domain.repository.UserRepository;
import com.example.demo.domain.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * 用户验证类,实现spring security提供的接口UserDetailService
 * 主要用来和数据库做交互，即用户名传递过来，该类负责校验用户名是否存在等业务
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private UserRepository userRepository;

    public UserDetailsServiceImpl(UserRepository userRepository){
        this.userRepository=userRepository;
    }

    /** 
    * @Description:  重写接口UserDetailService中的loadUserByUsername方法
    * @Param:  username:用户名
    * @return:  
    * @Author: wangze 
    */ 
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        User user = userRepository.findByUsername(username);
        if(user == null){
            throw new UsernameNotFoundException(username);
        }
        return user;
    }
}
